import 'dart:async';
import 'package:ai_model/app/core/network/core/api_client.dart';
import 'package:ai_model/app/core/network/extensions/api_extensions.dart';
import 'package:ai_model/app/core/storage/pref_utils.dart';
import 'package:get/get.dart';

import '../../../routes/app_pages.dart';

class SplashController extends GetxController {
  final RxBool isLoading = true.obs;
  final ApiClient _apiClient = ApiClient();

  @override
  void onInit() {
    super.onInit();
    // 延迟执行检查登录状态，确保启动页面有足够的显示时间
    Future.delayed(const Duration(seconds: 2), checkLoginStatus);
  }

  // 检查登录状态
  Future<void> checkLoginStatus() async {
    try {
      // 获取本地token
      final token = await PrefUtils().getToken();

      // 无token则直接跳转到登录页
      if (token.isEmpty) {
        Get.offAllNamed(Routes.LOGIN);
        return;
      }

      // 有token则验证token是否有效
      final response = await _apiClient.getLoginUserInfo();

      if (response.isSuccess && response.data != null) {
        // token有效，跳转到首页
        Get.offAllNamed(Routes.HOME);
      } else {
        // token无效，清除并跳转到登录页
        await PrefUtils().removeToken();
        Get.offAllNamed(Routes.LOGIN);
      }
    } catch (e) {
      // 发生异常，跳转到登录页
      print('Error checking login status: $e');
      await PrefUtils().removeToken();
      Get.offAllNamed(Routes.LOGIN);
    } finally {
      isLoading.value = false;
    }
  }
}
